﻿using System;
using System.Linq;
using System.Reflection;
using WeiTap.Data.Attributes;

namespace WeiTap.Data.Core
{
    public class TableInfo
    {
        public string TableName { get; set; }
        public string PrimaryKey { get; set; }
        public bool AutoIncrement { get; set; }
        public static TableInfo FromEntity(Type t) {
            TableInfo ti = new TableInfo();
            var a = t.GetCustomAttributes<TableNameAttribute>(true);
            ti.TableName = a.Count() == 0 ? t.Name : a.First().Name;

            var b =t.GetCustomAttributes<PrimaryKeyAttribute>(true);
            ti.PrimaryKey = b.Count() == 0 ? null : b.First().Name;
            ti.AutoIncrement = b.Count() == 0 ? false : b.First().AutoIncrement;
            if (string.IsNullOrEmpty(ti.PrimaryKey)) {
                var prop = t.GetProperties().FirstOrDefault(p => {
                    if (p.Name.Equals("id", StringComparison.OrdinalIgnoreCase))
                        return true;
                    return false;
                });
                if (prop != null) {
                    ti.PrimaryKey = prop.Name;
                    ti.AutoIncrement = prop.PropertyType.IsValueType;
                }
            }
            return ti;

        } 
    }
}